import axios from 'axios'
import { 
  classNames, 
  generateStudentAttendanceDetails, 
  generateAttendanceRecord,
  generateLeaveRecord,
  generateLeaveSchoolRecord
} from '../utils/mockDataGenerator'

// 创建axios实例
const request = axios.create({
  baseURL: '/api/attendance',
  timeout: 30000
})

// 添加请求拦截器
request.interceptors.request.use(
  config => {
    // 在请求发送之前获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  response => {
    return response
  },
  error => {
    console.error('请求出错:', error)
    return Promise.reject(error)
  }
)

// 动态生成模拟数据
// 生成班级列表
const generateClassList = () => {
  return classNames.map((className, index) => ({
    id: (index + 1).toString(),
    className
  }))
}

// 缓存数据 - 用于保持一致性
const cache = {
  classList: null,
  attendanceList: null,
  attendanceDetails: {},
  historyAttendance: null,
  leaveList: null,
  leaveSchoolList: null,
  attendanceSettings: null
}

// 生成考勤数据
const generateAttendanceList = () => {
  if (cache.attendanceList) {
    return cache.attendanceList
  }

  const attendanceList = [];
  const classes = generateClassList();
  const timePeriods = ['上午', '下午'];
  let id = 1;

  classes.forEach(classItem => {
    timePeriods.forEach(timePeriod => {
      attendanceList.push(generateAttendanceRecord(id.toString(), classItem.className, timePeriod));
      id++;
    });
  });

  cache.attendanceList = attendanceList;
  return attendanceList;
}

// 生成考勤详情数据
const generateAttendanceDetailsList = (attendanceId) => {
  if (cache.attendanceDetails[attendanceId]) {
    return cache.attendanceDetails[attendanceId];
  }

  // 查找对应的考勤记录以获取班级大小和缺勤数量
  const attendanceList = generateAttendanceList();
  const attendanceRecord = attendanceList.find(record => record.id === attendanceId);
  
  if (!attendanceRecord) {
    return [];
  }

  const details = generateStudentAttendanceDetails(attendanceRecord.total, attendanceRecord.absent);
  cache.attendanceDetails[attendanceId] = details;
  
  return details;
}

// 生成历史考勤数据
const generateHistoryAttendanceList = () => {
  if (cache.historyAttendance) {
    return cache.historyAttendance;
  }
  
  const historyAttendance = [];
  const classes = generateClassList();
  const timePeriods = ['上午', '下午'];
  let id = 101;
  
  // 生成过去30天的历史数据
  const today = new Date();
  for (let i = 1; i <= 15; i++) {
    const pastDate = new Date(today);
    pastDate.setDate(today.getDate() - i);
    const dateString = pastDate.toISOString().split('T')[0];
    
    classes.slice(0, 3).forEach(classItem => { // 只使用前3个班级以减少数据量
      timePeriods.forEach(timePeriod => {
        const record = generateAttendanceRecord(id.toString(), classItem.className, timePeriod, dateString);
        historyAttendance.push(record);
        id++;
      });
    });
  }
  
  cache.historyAttendance = historyAttendance;
  return historyAttendance;
}

// 生成请假数据
const generateLeaveList = () => {
  if (cache.leaveList) {
    return cache.leaveList;
  }
  
  const leaveList = [];
  const classes = generateClassList();
  let id = 201;
  
  // 为每个班级生成5条请假记录
  classes.forEach(classItem => {
    for (let i = 0; i < 5; i++) {
      leaveList.push(generateLeaveRecord(id.toString(), classItem.className));
      id++;
    }
  });
  
  cache.leaveList = leaveList;
  return leaveList;
}

// 生成离校数据
const generateLeaveSchoolList = () => {
  if (cache.leaveSchoolList) {
    return cache.leaveSchoolList;
  }
  
  const leaveSchoolList = [];
  const classes = generateClassList();
  let id = 301;
  
  // 为每个班级生成4条离校记录
  classes.forEach(classItem => {
    for (let i = 0; i < 4; i++) {
      leaveSchoolList.push(generateLeaveSchoolRecord(id.toString(), classItem.className));
      id++;
    }
  });
  
  cache.leaveSchoolList = leaveSchoolList;
  return leaveSchoolList;
}

// 考勤设置
const generateAttendanceSettings = () => {
  if (cache.attendanceSettings) {
    return cache.attendanceSettings;
  }
  
  const settings = [
    { id: '401', name: '上午考勤', startTime: '08:00', endTime: '08:30', status: '启用' },
    { id: '402', name: '下午考勤', startTime: '13:30', endTime: '14:00', status: '启用' }
  ];
  
  cache.attendanceSettings = settings;
  return settings;
}

// 重置缓存，用于模拟数据更新
export function resetCache() {
  for (const key in cache) {
    if (key === 'attendanceDetails') {
      cache[key] = {};
    } else {
      cache[key] = null;
    }
  }
}

// 是否使用模拟数据
const USE_MOCK = true

// 获取班级列表
export function getClassList() {
  if (USE_MOCK) {
    return Promise.resolve({
      data: {
        code: 200,
        message: '成功',
        data: generateClassList()
      }
    })
  }
  
  return request({
    url: '/class/list',
    method: 'get'
  })
}

// 获取今日考勤数据
export function getTodayAttendance(params) {
  if (USE_MOCK) {
    // 根据查询条件筛选数据
    let filteredData = [...generateAttendanceList()]
    
    if (params.className) {
      filteredData = filteredData.filter(item => item.className === params.className)
    }
    
    if (params.timePeriod) {
      filteredData = filteredData.filter(item => item.timePeriod === params.timePeriod)
    }
    
    // 模拟API延迟
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            code: 200,
            message: '成功',
            data: filteredData
          }
        })
      }, 300)
    })
  }
  
  return request({
    url: '/attendance/today',
    method: 'get',
    params
  })
}

// 获取考勤详情
export function getAttendanceDetail(id) {
  if (USE_MOCK) {
    // 模拟API延迟
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            code: 200,
            message: '成功',
            data: generateAttendanceDetailsList(id)
          }
        })
      }, 400)
    })
  }
  
  return request({
    url: `/attendance/detail/${id}`,
    method: 'get'
  })
}

// 获取历史考勤数据
export function getHistoryAttendance(params) {
  if (USE_MOCK) {
    let filteredData = [...generateHistoryAttendanceList()]
    
    if (params.className) {
      filteredData = filteredData.filter(item => item.className === params.className)
    }
    
    if (params.startDate && params.endDate) {
      filteredData = filteredData.filter(item => 
        item.date >= params.startDate && item.date <= params.endDate
      )
    }
    
    // 模拟API延迟
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            code: 200,
            message: '成功',
            data: filteredData
          }
        })
      }, 350)
    })
  }
  
  return request({
    url: '/attendance/history',
    method: 'get',
    params
  })
}

// 获取请假列表
export function getLeaveList(params) {
  if (USE_MOCK) {
    let filteredData = [...generateLeaveList()]
    
    if (params.className) {
      filteredData = filteredData.filter(item => item.className === params.className)
    }
    
    if (params.status) {
      filteredData = filteredData.filter(item => item.status === params.status)
    }
    
    if (params.leaveType) {
      filteredData = filteredData.filter(item => item.leaveType === params.leaveType)
    }
    
    if (params.studentName) {
      filteredData = filteredData.filter(item => 
        item.studentName.includes(params.studentName)
      )
    }
    
    // 模拟API延迟
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            code: 200,
            message: '成功',
            data: filteredData
          }
        })
      }, 300)
    })
  }
  
  return request({
    url: '/leave/list',
    method: 'get',
    params
  })
}

// 审批请假
export function approveLeave(id, data) {
  if (USE_MOCK) {
    // 更新缓存中的请假记录
    if (cache.leaveList) {
      const leaveIndex = cache.leaveList.findIndex(item => item.id === id);
      if (leaveIndex !== -1) {
        cache.leaveList[leaveIndex] = {
          ...cache.leaveList[leaveIndex],
          status: data.status,
          approver: data.approver
        };
      }
    }
    
    // 模拟API延迟
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            code: 200,
            message: '审批成功',
            data: null
          }
        })
      }, 500)
    })
  }
  
  return request({
    url: `/leave/approve/${id}`,
    method: 'post',
    data
  })
}

// 获取离校管理列表
export function getLeaveSchoolList(params) {
  if (USE_MOCK) {
    let filteredData = [...generateLeaveSchoolList()]
    
    if (params.className) {
      filteredData = filteredData.filter(item => item.className === params.className)
    }
    
    if (params.status) {
      filteredData = filteredData.filter(item => item.status === params.status)
    }
    
    if (params.date) {
      filteredData = filteredData.filter(item => item.leaveTime.startsWith(params.date))
    }
    
    // 模拟API延迟
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            code: 200,
            message: '成功',
            data: filteredData
          }
        })
      }, 300)
    })
  }
  
  return request({
    url: '/leaveSchool/list',
    method: 'get',
    params
  })
}

// 审批离校申请
export function approveLeaveSchool(id, data) {
  if (USE_MOCK) {
    // 更新缓存中的离校记录
    if (cache.leaveSchoolList) {
      const leaveSchoolIndex = cache.leaveSchoolList.findIndex(item => item.id === id);
      if (leaveSchoolIndex !== -1) {
        cache.leaveSchoolList[leaveSchoolIndex] = {
          ...cache.leaveSchoolList[leaveSchoolIndex],
          status: data.status
        };
      }
    }
    
    // 模拟API延迟
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            code: 200,
            message: '审批成功',
            data: null
          }
        })
      }, 500)
    })
  }
  
  return request({
    url: `/leaveSchool/approve/${id}`,
    method: 'post',
    data
  })
}

// 获取考勤设置
export function getAttendanceSettings() {
  if (USE_MOCK) {
    return Promise.resolve({
      data: {
        code: 200,
        message: '成功',
        data: generateAttendanceSettings()
      }
    })
  }
  
  return request({
    url: '/attendance/settings',
    method: 'get'
  })
}

// 更新考勤设置
export function updateAttendanceSettings(data) {
  if (USE_MOCK) {
    // 更新缓存
    cache.attendanceSettings = data;
    
    // 模拟API延迟
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            code: 200,
            message: '更新成功',
            data: null
          }
        })
      }, 500)
    })
  }
  
  return request({
    url: '/attendance/settings',
    method: 'post',
    data
  })
}

// 手动录入考勤记录
export function manualRecordAttendance(data) {
  if (USE_MOCK) {
    console.log('收到手动录入考勤数据:', data);
    
    // 生成唯一ID
    const id = (Date.now() + Math.floor(Math.random() * 1000)).toString();
    
    // 处理录入的考勤记录
    const newAttendanceRecord = {
      id,
      date: data.date || new Date().toISOString().split('T')[0],
      timePeriod: data.timePeriod || '上午',
      className: data.className || '一年级（1）班',
      total: data.records ? data.records.length : 0,
      present: data.records ? data.records.filter(r => r.status === '正常').length : 0,
      absent: data.records ? data.records.filter(r => r.status !== '正常').length : 0,
      attendanceRate: '0%'
    };
    
    // 计算出勤率
    if (newAttendanceRecord.total > 0) {
      newAttendanceRecord.attendanceRate = Math.round(newAttendanceRecord.present / newAttendanceRecord.total * 100) + '%';
    }
    
    console.log('生成的考勤记录:', newAttendanceRecord);
    
    // 确保缓存已初始化
    if (!cache.attendanceList) {
      generateAttendanceList();
    }
    
    // 将考勤记录添加到考勤列表
    cache.attendanceList.unshift(newAttendanceRecord);
    
    // 保存考勤详情
    if (data.records && data.records.length > 0) {
      cache.attendanceDetails[id] = data.records.map(record => ({
        studentName: record.studentName || '未知学生',
        studentId: record.studentId || '000000',
        status: record.status || '正常',
        reason: record.reason || ''
      }));
    }
    
    console.log('更新后的考勤列表:', cache.attendanceList);
    console.log('更新后的考勤详情:', cache.attendanceDetails[id]);
    
    // 模拟API延迟
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            code: 200,
            message: '录入成功',
            data: {
              attendanceRecord: newAttendanceRecord,
              details: cache.attendanceDetails[id]
            }
          }
        })
      }, 600)
    })
  }
  
  return request({
    url: '/attendance/record',
    method: 'post',
    data
  })
}

// 导出考勤数据
export function exportAttendanceData(params) {
  if (USE_MOCK) {
    // 模拟导出功能，实际上只返回成功消息
    // 模拟API延迟
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            code: 200,
            message: '导出成功',
            data: null
          }
        })
      }, 800)
    })
  }
  
  return request({
    url: '/attendance/export',
    method: 'get',
    params,
    responseType: 'blob'
  })
}

// 添加一条新的请假记录
export function addLeaveRecord(leaveData) {
  // 确保cache.leaveList已初始化
  if (!cache.leaveList) {
    generateLeaveList();
  }
  
  // 为新记录生成ID
  const newId = (parseInt(cache.leaveList[0]?.id || '200') + 1).toString();
  
  // 创建新的记录对象
  const newLeave = {
    id: newId,
    ...leaveData,
    status: leaveData.status || '待审批',
    approver: leaveData.approver || ''
  };
  
  // 添加到缓存的请假列表中
  cache.leaveList.unshift(newLeave);
  
  // 模拟API延迟
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        data: {
          code: 200,
          message: '添加成功',
          data: newLeave
        }
      });
    }, 500);
  });
}

// 添加一条新的离校记录
export function addLeaveSchoolRecord(leaveSchoolData) {
  console.log('API 接收到的离校数据:', leaveSchoolData); // 调试信息
  
  // 确保cache.leaveSchoolList已初始化
  if (!cache.leaveSchoolList) {
    generateLeaveSchoolList();
  }
  
  // 为新记录生成ID
  const newId = (parseInt(cache.leaveSchoolList[0]?.id || '300') + 1).toString();
  
  // 创建新的记录对象
  const newLeaveSchool = {
    id: newId,
    ...leaveSchoolData,
    status: leaveSchoolData.status || '待审批'
  };
  
  console.log('准备添加到缓存的离校记录:', newLeaveSchool); // 调试信息
  
  // 添加到缓存的离校列表中 (确保添加到列表的开头以便立即显示)
  cache.leaveSchoolList.unshift(newLeaveSchool);
  
  console.log('添加后缓存中的离校记录数:', cache.leaveSchoolList.length); // 调试信息
  
  // 模拟API延迟
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        data: {
          code: 200,
          message: '添加成功',
          data: newLeaveSchool
        }
      });
    }, 500);
  });
} 